package com.guiwu.gteway.industryapp;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.guiwu.gteway.industryapp.ChangePassword.ChangeActivity;
import com.guiwu.gteway.industryapp.Device.View.DeviceListFragment;
import com.guiwu.gteway.industryapp.Data.DataRepository;
import com.guiwu.gteway.industryapp.Device.module.GateWay;
import com.guiwu.gteway.industryapp.Device.module.GateWayGroup;
import com.guiwu.gteway.industryapp.Device.module.User;
import com.guiwu.gteway.industryapp.Map.GuiwuMapFragment;
import com.guiwu.gteway.industryapp.util.SoftKeyboardStateHelper;
import com.guiwu.gteway.industryapp.widget.MViewPager;

import com.guiwu.gteway.industryapp.widget.SearchEditText;
import com.guiwu.gteway.industryapp.widget.SimpleToolbar;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 主页面
 */
public class MainActivity extends RootActivity {
    private static final String TAG = "MainActivity";

    private DrawerLayout mDrawerLayout;
    private MViewPager mViewPager;
    private TabLayout mTabLayout;
    private List<GateWayGroup> mGateWayGroups = new ArrayList<>();
    private FragmentAdapter fragmentAdapter;
    private SimpleToolbar toolbar;
    private SearchEditText mGateWaysearch;
    private User mUser;


    public static Intent newIntent(Context PackageContext){
        Intent intent = new Intent(PackageContext,MainActivity.class);
        //intent.putExtra()
        return intent;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        initView();
        initViewPager();
       // initData();
    }


    private void initView(){
        toolbar = findViewById(R.id.main_simple_toolbar);
        mViewPager = findViewById(R.id.view_pager);
        mGateWaysearch = findViewById(R.id.gateway_search);

        //监听键盘上下
        final SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(findViewById(R.id.main_parent_layout));
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {

            }

            @Override
            public void onSoftKeyboardClosed() {
                mGateWaysearch.clearFocus();
                searchGateWays(mGateWaysearch.getText().toString());
            }
        });

        mGateWaysearch.setOnSearchClickListener(new SearchEditText.OnSearchClickListener() {
            @Override
            public void onSearchClick(View view) {

            }
        });


        //
        mDrawerLayout = findViewById(R.id.dl_main_drawer);
        NavigationView navigationView = findViewById(R.id.nv_main_navigation);
        if (navigationView != null){
            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    item.setChecked(true);
                    handlerNvItem(item.getItemId());
                    mDrawerLayout.closeDrawers();
                    return true;
                }
            });
        }

        toolbar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
        });
    }

    private void handlerNvItem(int id){
        switch (id){
            case R.id.quit_login:
                finish();
                break;
            case R.id.change_paw:
                startActivity(ChangeActivity.newIntent(MainActivity.this));
                break;
        }
    }

    private void searchGateWays(String key){
        if (key == null || key.equals("")){ //什么都没搜
            ((GuiwuMapFragment)getFragments().get(0)).getGateGroups();
        }else {
            query(key,mGateWayGroups);
            Log.i(TAG, "searchGateWays: " + mGateWayGroups);
            updateView();
        }
    }

    private void updateView(){
        ((DeviceListFragment)getFragments().get(1)).updateUI();

        List<GateWay> newGates = new ArrayList<>();
        for (GateWayGroup group : mGateWayGroups){
            newGates.addAll(group.getGateWays());
        }
        ((GuiwuMapFragment)getFragments().get(0)).addOverLay(newGates);
    }

    private void query(String key , List<GateWayGroup> gateWayGroups){
        for (Iterator<GateWayGroup> itGroup = gateWayGroups.iterator();
                itGroup.hasNext();){
            GateWayGroup group = itGroup.next();
            List<GateWay> gateWayList = group.getGateWays();
            Iterator<GateWay> itGateWay  = gateWayList.iterator();

            while (itGateWay.hasNext()){
                GateWay per = itGateWay.next();
                if (!per.getGateWayName().contains(key))
                    itGateWay.remove();
            }

            if (gateWayList.size() == 0)
                itGroup.remove();
        }
    }

    private List<GateWay> queryMatch(String keyWords, List<GateWay> gateWays){
        List<GateWay> returnList = new ArrayList<>();
        for (GateWay per : gateWays){
            if (per.getGateWayName().contains(keyWords))
                returnList.add(per);
        }
        return returnList;
    }



    private void initViewPager(){
        mTabLayout = findViewById(R.id.tabs);
        List<String> titles = new ArrayList<>();
        titles.add("地图");
        titles.add("控制");

        for (int i = 0; i< titles.size();i++){
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
        }

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new GuiwuMapFragment());
        fragments.add(new DeviceListFragment());
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(),fragments,titles);
        //给ViewPager设置适配器
        mViewPager.setAdapter(fragmentAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabsFromPagerAdapter(fragmentAdapter);
    }

    private class FragmentAdapter extends FragmentStatePagerAdapter{
        private List<Fragment> mFragments;
        private List<String> mTitls;

        public FragmentAdapter(FragmentManager fm,List<Fragment> fragments,List<String> titles){
            super(fm);
            mFragments = fragments;
            mTitls = titles;
        }
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitls.get(position);
        }
    }

    public List<Fragment> getFragments(){
       return fragmentAdapter.mFragments;
    }

    public List<GateWayGroup> getmGateWayGroups() {
        return mGateWayGroups;
    }

    public void setmGateWayGroups(List<GateWayGroup> mGateWayGroups) {
        this.mGateWayGroups = mGateWayGroups;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataRepository.getInstance().clearUser();
    }
}
